import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A Servlet to help view jpg images
 *
 * @author James Chy
 */

public class SaveFiles extends PhotoServlet {

    String subtitle;
    int i;
    String sessionid;
    static final long serialVersionUID = 0;
    
    public void init() 
    {
    	subtitle = "Save Files";
    }
    
    public void doPost(HttpServletRequest request,
                        HttpServletResponse response)
        throws IOException, ServletException
    {
    	
        String smallquery="";
            
        response.setContentType("text/html");
        out = response.getWriter();

        sessionid=request.getParameter("sessionid");
        boolean large=(request.getParameter("Large") != null &&
                request.getParameter("Large").equals("on") );

        out.println("<HTML><HEAD><TITLE>" + title + " - " + subtitle + "</TITLE></HEAD><BODY>");
            
        smallquery = "SELECT images.uid, images.image_file " +
					 "FROM images, session_results " +
					 "WHERE session_results.session_uid = " + sessionid + " " +
					 "AND images.uid = session_results.image_uid";

        if (showQuery) out.println(smallquery+"<BR>");
        ResultSet rs = this.executeQuery(smallquery);
        try
        {
            File newDir = new File(results + File.separator + String.valueOf(sessionid));
        	if(showQuery) out.println("Directory is " + newDir.getAbsolutePath());
            if(!newDir.exists()) 
        	{
        		boolean madeDir = newDir.mkdir();
                if (showQuery) 
                {
                	if(madeDir)
                	{
                    	out.println("Directory created"+"<BR>");
                	}
                	else 
                	{
                    	out.println("Directory not created"+"<BR>");
                	}
                }
        	}
        	if(newDir.exists()) 
        	{
            	out.println("Directory: " + sessionid + "<BR>");
            	while(rs.next())
                {
                	String image=rs.getString("images.image_file");
                	image = image.replaceAll("/", File.separator);
                	boolean dirOk = true;
                	if(image.lastIndexOf(File.separator) > -1)
                	{
                    	dirOk = false;
                		String imageDir = image.substring(0, image.lastIndexOf(File.separator));
                    	File subPath = new File(results + File.separator + String.valueOf(sessionid) + File.separator + imageDir);
                    	if(!subPath.exists()) 
                    	{
                        	boolean madeSubDirs = subPath.mkdirs();
                            if (showQuery) 
                            {
                            	if(madeSubDirs)
                            	{
                                	out.println("Directories created"+"<BR>");
                            	}
                            	else 
                            	{
                                	out.println("Directories not created"+"<BR>");
                            	}
                            }
                        	
                    	}
                    	
                    	if(subPath.exists()) 
                    	{
                        	dirOk = true;
                    	}
                	}
                	if(dirOk)
                	{
                		String source = (large ? oversize : start) + File.separator + image;
                    	String destination = results + File.separator + String.valueOf(sessionid) + File.separator + image;
                    	
                    	if(showQuery) {
                    		out.println("Source: " + source + "<BR>");
                    		out.println("Destination: " + destination + "<BR>");
                    	}
                    	
                    	boolean result = SaveFiles.copyfile(source, destination);
                    	out.println(image+" " + (result ? "copied" : "not copied") + " <BR>");
                	}
                }
        	}
        }
        catch(SQLException sqle)
        {
            out.println(sqle.getMessage());
        }
           
        out.println("<FORM ACTION=SearchResults METHOD=POST>");
        out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
        out.println("<INPUT TYPE=SUBMIT VALUE=\"Search Results\">");
        out.println("</FORM>");
        out.println("</BODY></HTML>");

    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        out = response.getWriter();
        ResultSet rs;

        out.println("<HTML>");
        out.println("<BODY BGCOLOR=\"white\">");
        out.println("<HEAD>");

        subtitle = "Save Files";

        sessionid=request.getParameter("sessionid");

        if(showQuery) out.println("sessionid: " + sessionid);

        out.println("<TITLE>" + title + " - " + subtitle + "</TITLE>");  
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<FORM ACTION=SearchResults METHOD=POST>");
        out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
        out.println("<INPUT TYPE=SUBMIT VALUE=\"Search Results\">");
        out.println("</FORM>");

        String getSession = "SELECT session_uid, image_file FROM session_results WHERE session_uid = " + sessionid + " ORDER BY (date), (image_file);";
        if(showQuery)
            out.println("Get Session: "+getSession+"<BR>");

        rs = executeQuery(getSession);

        try
        {
            for(i=1;rs.next(); i++) {
            	if(showQuery) 
            	   out.println(rs.getString("image_file") + "<BR>"); 
            }
            
            out.println((i-1)+" image(s).<BR>");
			
		}
		catch(SQLException sqle)
		{
			out.println("SQL Exception error "+sqle.toString() );
		}    

		rs = executeQuery(getSession);

        out.println("<FORM ACTION=SaveFiles METHOD=POST>");
        out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
        out.println("<INPUT TYPE=SUBMIT VALUE=\"Save Now\">");
        out.println("Large <INPUT TYPE=CHECKBOX NAME=\"Large\">");
        out.println("</FORM>");

        out.println("</BODY>");
        out.println("</HTML>");
    	
    }
}